/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.pay.api.PayLogApi;
import net.guerlab.smart.pay.api.feign.FeignPayLogApi;
import net.guerlab.smart.pay.core.domain.PayLogDTO;
import net.guerlab.smart.pay.core.exception.PayLogInvalidException;
import net.guerlab.smart.pay.core.searchparams.PayLogSearchParams;
import net.guerlab.spring.searchparams.SearchParamsUtils;
import net.guerlab.web.result.ListObject;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 支付记录服务接口feign实现
 *
 * @author guer
 */
@Configuration
@AutoConfigureAfter(PayLogApiLocalServiceAutoConfigure.class)
public class PayLogApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(PayLogApi.class)
    public PayLogApi payLogApiFeignWrapper(FeignPayLogApi api) {
        return new PayLogApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class PayLogApiFeignWrapper implements PayLogApi {

        private final FeignPayLogApi api;

        @Override
        public PayLogDTO findOne(Long payLogId) {
            return Optional.ofNullable(api.findOne(payLogId).getData()).orElseThrow(PayLogInvalidException::new);
        }

        @Override
        public ListObject<PayLogDTO> findList(PayLogSearchParams searchParams) {
            HashMap<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findList(params).getData()).orElse(ListObject.empty());
        }

        @Override
        public List<PayLogDTO> findAll(PayLogSearchParams searchParams) {
            HashMap<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findAll(params).getData()).orElse(Collections.emptyList());
        }
    }

}
